﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Ipmce.RemoteVoting.Common.Tools;
using Ipmce.RemoteVoting.Common.Tools.CardReader;
using Ipmce.RemoteVoting.Common.Tools.CardReader.Exceptions;
using Ipmce.RemoteVoting.Common.Tools.CardReader.ImageParsing;
using Ipmce.RemoteVoting.Frontend.VotingApplication.Properties;
using Ipmce.RemoteVoting.Frontend.VotingApplication.Utils;

namespace Ipmce.RemoteVoting.Frontend.VotingApplication.ViewModel
{
	class PassportAuthorizationViewModel : ViewModelBase, IPassportDataProvider
	{
		private readonly IPassportReader _passportReader;
		private readonly IPasswordCreator _passwordCreator;
		private readonly IImageParser _imageParser;
		private byte[] _rawDg2Data;

		public PassportAuthorizationViewModel(IPassportReader passportReader, IPasswordCreator passwordCreator,
			IImageParser imageParser)
		{
			_passportReader = passportReader;
			_passwordCreator = passwordCreator;
			_imageParser = imageParser;
			ScanCommand = new CommandViewModel(Resources.MainWindowViewModel_Command_Scan,
				CreateScanCommand());
		}

		private ICommand CreateScanCommand()
		{
			return new RelayCommand(o => Scan(), o => CanScan());
		}

		private void Scan()
		{
		    try
		    {
                _rawDg2Data = _passportReader.GetRawDg2Data(Mrz);
		    	ImageType imageType;
		    	var rawImage = _imageParser.ParseImage(_rawDg2Data, out imageType);
				using (var memStream = new MemoryStream(rawImage))
				{
					var decoder = new JpegBitmapDecoder(memStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
					FacialPicture = decoder.Frames[0];
		    	}
		    }
		    catch (PassportNotFoundException)
		    {
		        MessageBox.Show("Ошибка во время чтения паспорта. Паспорт не найден.", "Ошибка", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
		        return;
		    }
			Status = "Статус : данные считаны";
		}

	    private bool CanScan()
		{
			return !string.IsNullOrEmpty(Mrz);
		}

		public bool IsDataReady()
		{
			return _rawDg2Data != null && !string.IsNullOrEmpty(VoterPassportNumber) && !string.IsNullOrEmpty(Sms);
		}

		public string VoterPassportNumber { get; set; }

		public string VoterPassword
		{
			get
			{
				if (!IsDataReady())
				{
					throw new InvalidOperationException("Data ain't ready");
				}
				return _passwordCreator.CreatePassword(Sms, _rawDg2Data);
			}
		}

		public CommandViewModel ScanCommand { get; private set; }

		public string Sms { get; set; }

		public string Mrz { get; set; }

		public string Status
		{
			get
			{
				return _status;
			}
			private set
			{
				_status = value;
				OnPropertyChanged("Status");
			}
		}

		private ImageSource _facialPicture;
		public ImageSource FacialPicture
		{
			get
			{
				return _facialPicture;
			}
			set
			{
				_facialPicture = value;
				OnPropertyChanged("FacialPicture");
			}
		}

		private string _status = "Статус : не считано";
	}
}
